package com.dragon.english_practice_back.controller;


import com.dragon.english_practice_back.controller.dto.LoginDto;
import com.dragon.english_practice_back.controller.dto.RegisterDto;
import com.dragon.english_practice_back.entity.Role;
import com.dragon.english_practice_back.entity.User;
import com.dragon.english_practice_back.reponse.Result;
import com.dragon.english_practice_back.service.AuthenticationUtil;
import com.dragon.english_practice_back.service.LoginService;
import com.dragon.english_practice_back.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/start")
public class StartController {
    @Autowired
    LoginService loginService;
    @Autowired
    UserService userService;
    @Autowired
    private AuthenticationUtil authenticationUtil;

    @PostMapping("/login")
    public Object login(@RequestBody LoginDto loginDto){
        //解析dto
        User user = new User();
        user.setEmail(loginDto.getUserEmail());
        user.setPassword(loginDto.getPassword());

        return loginService.login(user);
    }

    // 注销
    @PostMapping("/logout")
    public Result logout(){
        // 注销
        return loginService.logout();
    }

    // 注册
    @PostMapping("/register")
    public Result register(@RequestBody RegisterDto registerDto){
        // 检查数据
        if (!registerDto.checkData()){
            return Result.no("数据不合法");
        }
        // 注册
        User user = new User();
        user.setEmail(registerDto.getEmail());
        user.setPassword(registerDto.getPassword());
        return loginService.register(user);
    }

    // 检查邮箱是否存在
    @PostMapping("/checkEmailIsAvailable")
    public Result checkEmail(@RequestBody RegisterDto registerDto){
        // 检查邮箱是否存在
        return loginService.existEmail(registerDto.getEmail())? Result.no("邮箱已存在"): Result.ok("邮箱不存在,可以使用");
    }

    //获取用户信息
    @GetMapping("/getUserInfo")
    public Result<User> getUserInfo(){
        // 获取用户信息
        User user = userService.getById(authenticationUtil.id());
        user.setPassword(null);
        return new Result<>(200, "用户信息", user);
    }

    //获取用户角色
    @GetMapping("/getUserRole")
    public Result<List<Role>> getUserRole(@RequestParam Integer id){
        // 获取用户角色
        return new Result<>(200, "用户角色集合", loginService.role());

    }


}
